//
//  AlbumViewController.m
//  ProjectSource_Demo
//
//  Created by Liu on 16/2/1.
//  Copyright © 2016年 AngryBear. All rights reserved.
//

#import "AlbumViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "AlbumPreviewVC.h"

#import "AlbumImageCell.h"
#import "AlbumTabbar.h"

@interface AlbumViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) AlbumTabbar *albumTabbar;
@property (nonatomic, strong) NSMutableArray *imagesArray;
@property (nonatomic, strong) NSMutableArray *selectedImagesArray;

@end

@implementation AlbumViewController

- (void)dealloc
{

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayBG];
    self.imagesArray = [NSMutableArray array];
    self.selectedImagesArray = [NSMutableArray array];
    
    [self setSubviews];
    [self setupRACObserveMethods];
    [self imagesFromAlbum];
}

- (void)setSubviews
{
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.albumTabbar];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.top.mas_equalTo(0);
        make.bottom.equalTo(self.view).with.offset(-50);
    }];
    
    [self.albumTabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.bottom.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
}

- (void)addPhotoLibraryAuthorizationStatusDeniedView
{
    self.collectionView.hidden = YES;
    self.albumTabbar.hidden = YES;
    
    [self.view addSubview:self.statusLabel];
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(10, 10, 10, 10));
    }];
}

- (void)setupRACObserveMethods
{
    /*
    [[self.albumTabbar.previewButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        NSLog(@"preview %@", self.selectedImagesArray);
        
        AlbumPreviewVC *vc = [[AlbumPreviewVC alloc] init];
        [vc albumPreviewShowImages:self.selectedImagesArray];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [[self.albumTabbar.sendButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        NSLog(@"send %@", self.selectedImagesArray);
    }];
     */
}

- (void)imagesFromAlbum
{
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
        [self getImageByAssetsLibrary];
    }
    else {
        [self getImageByPhotoKit];
    }
}

- (void)getImageByAssetsLibrary
{
    if ([ALAssetsLibrary authorizationStatus] != ALAuthorizationStatusAuthorized) {
        [self addPhotoLibraryAuthorizationStatusDeniedView];
        return;
    }
    ALAssetsLibrary *library = [ALAssetsLibrary new];
    [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                UIImage *image = [[UIImage alloc] initWithCGImage:result.thumbnail];
                if (image) {
                    [self.imagesArray addObject:image];
                }
            }];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.collectionView.hidden = NO;
                self.albumTabbar.hidden = NO;
                [self.collectionView reloadData];
            });
        }
    } failureBlock:^(NSError *error) {
        if ([error.localizedDescription rangeOfString:@"Global denied access"].location != NSNotFound) {
            NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态.");
        }
        else {
            NSLog(@"相册访问失败.");
        }
    }];
}

- (void)getImageByPhotoKit
{
    if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
        if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                [self getImageByPhotoKit];
            }];
            return;
        }
        [self addPhotoLibraryAuthorizationStatusDeniedView];
        return;
    }
    
    PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
    allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *result = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
    for (int i = 0; i < result.count; i++) {
        PHAsset *asset = [result objectAtIndex:i];
        [self.imagesArray addObject:asset];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectionView.hidden = NO;
        self.albumTabbar.hidden = NO;
        [self.collectionView reloadData];
    });
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imagesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AlbumImageCell class]) forIndexPath:indexPath];
    id obj = [self.imagesArray objectAtIndex:indexPath.row];
    if ([obj isKindOfClass:[UIImage class]]) {
        cell.imageView.image = obj;
    }
    else if ([obj isKindOfClass:[PHAsset class]]) {
        CGFloat width = ([UIScreen mainScreen].bounds.size.width - 5*5)/4;
        CGFloat scale = [UIScreen mainScreen].scale;
        CGSize size = CGSizeMake(width*scale, width*scale);
        [[PHImageManager defaultManager] requestImageForAsset:obj targetSize:size contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            if (result) {
                cell.imageView.image = result;
            }
        }];
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"reuseableView" forIndexPath:indexPath];
    view.backgroundColor = [UIColor redColor];
    return view;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = [self.imagesArray objectAtIndex:indexPath.row];
    if (![self.selectedImagesArray containsObject:obj]) {
        [self.selectedImagesArray addObject:obj];
    }
    [self setTabbarSendButtonTitle];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = [self.imagesArray objectAtIndex:indexPath.row];
    if ([self.selectedImagesArray containsObject:obj]) {
        [self.selectedImagesArray removeObject:obj];
    }
    [self setTabbarSendButtonTitle];
}

- (void)setTabbarSendButtonTitle
{
    NSString *title = @"  发送  ";
    if (self.selectedImagesArray.count) {
        title = [NSString stringWithFormat:@" 发送(%ld/%ld) ", self.selectedImagesArray.count, self.imagesArray.count];
        self.albumTabbar.sendButton.enabled = YES;
    }
    else {
        self.albumTabbar.sendButton.enabled = NO;
        
    }
    [self.albumTabbar.sendButton setTitle:title forState:UIControlStateNormal];
}

#pragma mark - Property Methods
- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat lineSpace = 5;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = ([UIScreen mainScreen].bounds.size.width - lineSpace*5)/4;
        layout.itemSize = CGSizeMake(width, width);
        layout.sectionInset = UIEdgeInsetsMake(lineSpace, lineSpace, lineSpace, lineSpace);
        layout.minimumInteritemSpacing = lineSpace;
        layout.minimumLineSpacing = lineSpace;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor grayBG];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.allowsMultipleSelection = YES;
        
        [_collectionView registerClass:[AlbumImageCell class] forCellWithReuseIdentifier:NSStringFromClass([AlbumImageCell class])];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"reuseableView"];
    }
    return _collectionView;
}

- (AlbumTabbar *)albumTabbar
{
    if (!_albumTabbar) {
        _albumTabbar = [[AlbumTabbar alloc] initWithFrame:CGRectZero];
        _albumTabbar.backgroundColor = [UIColor whiteColor];
    }
    return _albumTabbar;
}

- (UILabel *)statusLabel
{
    if (!_statusLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.backgroundColor = [UIColor clearColor];
        label.numberOfLines = 0;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:16];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"请在iPhone的“设置－隐私－照片”选项中，允许卷皮访问你的手机相册。";
        _statusLabel = label;
    }
    return _statusLabel;
}

@end

